Material Design 之 侧边栏与 Status Bar 不得不说的故事

再过2个小时就是2015苹果春季发布会了,在两个小时的闲暇时间里,顺便鼓捣一下 Material Design 的侧边栏,没想到又是心酸血泪史。

Material Design 中,侧边栏是一个可以从屏幕左侧滑出的抽屉式的组件。如下效果图所示,当侧边栏滑出时,它处于 Status Bar 之下,并且覆盖了 Status Bar 原有的颜色(图中 Dark Primary Color 所指组件)。按照 Material Design 中 Status Bar 的设计,Status Bar 的颜色会深于 ActionBar (图中 Primary Color 所指组件),效果图由于压缩的原因,可能不太明显。

效果图

所以,要实现如下效果,有如下3件事需要完成:

  • 为了能使 ActionBar 获得最大的扩展,我们使用 ToolBar 代替 ActionBar,并将其颜色设置为 Material Design 中的 Primary Color
  • 将 Status Bar 的颜色设置为 Material Design 中的 Dark Primary Color
  • 将侧边栏插入于 Status Bar 和 页面内容之间

前两步中,正常的实现方式如下:

values-v21/styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light">
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="windowActionBar">false</item>
        <item name="android:colorPrimary">@color/theme_primary</item>
        <item name="android:colorPrimaryDark">@color/theme_dark_primary</item>
</style>

运行程序,效果正是我们想要的(请不要在意配色怎么这么丑的细节, = =)。

效果图

下面,按照我们正常的方式添加侧边栏组件,为了能使侧边栏正常的显示在 Status Bar 之下,在 values-v21/styles.xml中添加入

<item name="android:windowTranslucentStatus">true</item>

并将 Activity 继承自 ActionBarActivity, 并使用如下布局:

<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <RelativeLayout
        android:id="@+id/content_relative"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">
        <include
            android:id="@+id/toolbar"
            layout="@layout/framelayout_toolbar_with_search"/>
        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/toolbar"
            android:background="@android:color/white">
        </FrameLayout>
    </RelativeLayout>
    <!-- navigation 中根目录已经添加  android:fitsSystemWindows="false" 属性 -->
    <include layout="@layout/navigation"/>
</android.support.v4.widget.DrawerLayout>

duang! 问题出现了,侧边栏正常显示,但是之前设置的 Status Bar 的颜色失效了。

Status Bar 的颜色失效

但是,将刚才添加的状态栏透明的属性删除

<item name="android:windowTranslucentStatus">true</item>

duang!duang! 问题又出现了,侧边栏根本没有在 SystemBar 之下。

侧边栏没有在 Status Bar 之下

擦擦擦,这两个属性冲突了

<item name="android:windowTranslucentStatus">true</item>
<item name="android:windowDrawsSystemBarBackgrounds">true</item>

为了解决这个问题,我拆解了谷歌官方应用,终于发现了这个秘密(可能是我才疏学浅,后来才发现官方的 Android Demo 里就有, 哈哈)

所以现在是解决问题的时间了。

首先,需要在应用中添加 ScrimInsetsFrameLayout 开源组件。

** ScrimInsetsFrameLayout.java **

/*
 * Copyright 2014 Google Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.samples.apps.iosched.ui.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.widget.FrameLayout;

import com.google.samples.apps.iosched.R;

/**
 * A layout that draws something in the insets passed to {@link #fitSystemWindows(Rect)}, i.e. the area above UI chrome
 * (status and navigation bars, overlay action bars).
 */
public class ScrimInsetsFrameLayout extends FrameLayout {
    private Drawable mInsetForeground;

    private Rect mInsets;
    private Rect mTempRect = new Rect();
    private OnInsetsCallback mOnInsetsCallback;

    public ScrimInsetsFrameLayout(Context context) {
        super(context);
        init(context, null, 0);
    }

    public ScrimInsetsFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }

    public ScrimInsetsFrameLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    private void init(Context context, AttributeSet attrs, int defStyle) {
        final TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.ScrimInsetsView, defStyle, 0);
        if (a == null) {
            return;
        }
        mInsetForeground = a.getDrawable(R.styleable.ScrimInsetsView_insetForeground);
        a.recycle();

        setWillNotDraw(true);
    }

    @Override
    protected boolean fitSystemWindows(Rect insets) {
        mInsets = new Rect(insets);
        setWillNotDraw(mInsetForeground == null);
        ViewCompat.postInvalidateOnAnimation(this);
        if (mOnInsetsCallback != null) {
            mOnInsetsCallback.onInsetsChanged(insets);
        }
        return true; // consume insets
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);

        int width = getWidth();
        int height = getHeight();
        if (mInsets != null && mInsetForeground != null) {
            int sc = canvas.save();
            canvas.translate(getScrollX(), getScrollY());

            // Top
            mTempRect.set(0, 0, width, mInsets.top);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            // Bottom
            mTempRect.set(0, height - mInsets.bottom, width, height);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            // Left
            mTempRect.set(0, mInsets.top, mInsets.left, height - mInsets.bottom);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            // Right
            mTempRect.set(width - mInsets.right, mInsets.top, width, height - mInsets.bottom);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            canvas.restoreToCount(sc);
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (mInsetForeground != null) {
            mInsetForeground.setCallback(this);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mInsetForeground != null) {
            mInsetForeground.setCallback(null);
        }
    }

    /**
     * Allows the calling container to specify a callback for custom processing when insets change (i.e. when
     * {@link #fitSystemWindows(Rect)} is called. This is useful for setting padding on UI elements based on
     * UI chrome insets (e.g. a Google Map or a ListView). When using with ListView or GridView, remember to set
     * clipToPadding to false.
     */
    public void setOnInsetsCallback(OnInsetsCallback onInsetsCallback) {
        mOnInsetsCallback = onInsetsCallback;
    }

    public static interface OnInsetsCallback {
        public void onInsetsChanged(Rect insets);
    }
}

然后创建该组件的自定义属性,使组件的 insetForeground 属性生效

values/attrs.xml

<declare-styleable name="ScrimInsetsView"> 
    <attr name="insetForeground" format="reference|color" />
</declare-styleable>

更新你的 Activity 的布局文件,需要注意的是,确保 DrawerLayout 和 ScrimInsetsFrameLayout 都添加了 android:fitsSystemWindows 属性,并设置为 true

layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">
    <RelativeLayout
        android:id="@+id/content_relative"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <include
            android:id="@+id/toolbar"
            layout="@layout/framelayout_toolbar_with_search"/>
        <FrameLayout
            android:id="@+id/content_frame"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_below="@id/toolbar"
            android:background="@android:color/white">
        </FrameLayout>
    </RelativeLayout>
    <com.google.samples.apps.iosched.ui.widget.ScrimInsetsFrameLayout
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/scrimInsetsFrameLayout"
        android:layout_width="@dimen/navigation_width"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:elevation="10dp"
        android:fitsSystemWindows="true"
        app:insetForeground="#4000">
        <include layout="@layout/navigation"/>
    </com.google.samples.apps.iosched.ui.widget.ScrimInsetsFrameLayout>
</android.support.v4.widget.DrawerLayout>

最后,更新主题文件,使侧边栏显示与 Status Bar 之下

values-v21/styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light">
        <item name="android:windowDrawsSystemBarBackgrounds">true</item>
        <item name="windowActionBar">false</item>
        <item name="android:colorPrimary">@color/theme_primary</item>
        <item name="android:colorPrimaryDark">@color/theme_dark_primary</item>
        <item name="android:statusBarColor">@android:color/transparent</item>
</style>

最最后,就是见证奇迹的时刻(边看直播边码文字,刚好在发布会结束时完成,Macbook 很赞,Apple Watch 除外观之外,还不错的说)

最终效果图
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,569评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,499评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,271评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,087评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,474评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,670评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,911评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,636评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,397评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,607评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,093评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,418评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,074评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,092评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,865评论 0 196
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,726评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,627评论 2 270

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 170,569评论 25 707
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,617评论 4 59
  • afinalAfinal是一个android的ioc,orm框架 https://github.com/yangf...
    passiontim阅读 15,088评论 2 44
  • 目录 上一章 引路 10车20号下铺 吴孟宇 文字编辑 37kg 一. “赴一场狂欢,跳...
    景泰蓝呦阅读 236评论 0 0
  • 民以食为天,吃饭永远是人们生活中最重要的一部分。但随着物质水平的提高,大家追求的美食已经不仅仅停留在吃得饱就可以了...
    爱生活爱巴西阅读 365评论 0 1